package com.shiro.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * <p>
 *
 * </p>
 *
 * @author liup
 * @since 2020/10/20
 */
@Controller
public class LoginController {

    @RequestMapping({"/","/index"})
    public String goIndex(Model model){
        model.addAttribute("msg","hello shiro !");
        model.addAttribute("content","Three core objects ：ShiroFilterFactoryBean、SecurityManager、Realm !");
        return "index";
    }

    @RequestMapping("login")
    public String login(){
        return "login";
    }

    @RequestMapping("doLogin")
    public String doLogin(String username,String password,Model model){

        Subject subject = SecurityUtils.getSubject();
        //获取 用户名和密码的token值
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try{
            //使用令牌值执行登录
            subject.login(token);
            //登录通过，设置前端展示内容
            model.addAttribute("username",username);
            //登录成功调转
            return "index";

        }catch (UnknownAccountException e){
            //用户名不存在
            model.addAttribute("loginmsg","用户名不存在！");
            return "login";
        }
        catch (IncorrectCredentialsException e){
            //密码错误
            model.addAttribute("loginmsg","密码错误！");
            return "login";
        }
        catch (UnauthorizedException e){
            //未授权错误
            return "nauth";
        }
        catch (LockedAccountException e){
            model.addAttribute("loginmsg","账户已被锁定，不可登录！");
            return "login";
        }
    }

    @RequestMapping("user/add")
    public String toAddPage(){
        return "user/add";
    }

    @RequestMapping("user/update")
    public String toUpdatePage(){
        return "user/update";
    }

    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }
    @RequestMapping("/nauth")
    public String toNauthPage(){
        return "nauth";
    }
}
